import CredentialsProvider from "next-auth/providers/credentials";
import type { NextAuthOptions } from "next-auth";

export const authOptions: NextAuthOptions = {
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        username: { label: "账号", type: "text" },
        password: { label: "密码", type: "password" },
      },
      async authorize(credentials) {
        const res = await fetch(
          `${process.env.BACKEND_URL}${process.env.NEXT_PUBLIC_API_URL}/user/login`,
          {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(credentials),
          }
        );

        const data = await res.json();

        console.log(data);

        if (res.ok && data.success) {
          return {
            id: data.id, // ✅ NextAuth 要求至少有 id 字段
            name: data.username,
            role: data.role,
          };
        }

        return null;
      },
    }),
  ],

  session: {
    strategy: "jwt",
  },

  callbacks: {
    async jwt({ token, user }) {
      if (user) {
        token.user = user; // ✅ 把 user 信息注入 JWT token
      }
      return token;
    },
    async session({ session, token }) {
      if (token.user) {
        session.user = token.user; // ✅ 再从 JWT token 注入到 session.user
      }
      return session;
    },
  },

  pages: {
    signIn: "/login",
    error: "/login?error=true",
  },

  secret: process.env.NEXTAUTH_SECRET,
};
